# encoding: utf-8
from functools import wraps

from flask import g, request
from exts import get_redis
# 登录限制的装饰器
from api.slider import get_json_response
from api.utils import get_login_name_from_token
from models import User


def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        g.user = None
        authorization = request.headers.get('Authorization', None)
        print(authorization)
        response_dict = {
            'err': True,
        }
        if authorization:
            login_name = get_login_name_from_token(authorization)
            if not login_name:
                return get_json_response(response_dict, request)
            login_user = User.query.filter(User.username == login_name).first()
            if login_user:
                g.user = login_user
            return func(*args, **kwargs)
        else:
            return get_json_response(response_dict, request)

    return wrapper


# 缓存装饰器
def cache(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        full_path = request.full_path
        value = get_redis(full_path)
        if value:
            print(type(value))
            return get_json_response(value, request, is_set_cache=False)
        else:
            return func(*args, **kwargs)

    return wrapper
